package database

import (
	"fmt"
	"gin_server/config"
	"log"
	"strconv"
	"time"

	"gin_server/internal/model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var db *gorm.DB

func InitDB() {
	var err error

	dbHost := config.AppConfig.Database.Host
	dbPort := config.AppConfig.Database.Port
	dbUser := config.AppConfig.Database.Username
	dbPassword := config.AppConfig.Database.Password
	dbName := config.AppConfig.Database.Name

	// 将 dbPort 转换为字符串
	dbPortStr := strconv.Itoa(dbPort)

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbUser, dbPassword, dbHost, dbPortStr, dbName)

	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect to database:", err)
	}

	// 获取通用数据库对象 sql.DB
	sqlDB, err := db.DB()
	if err != nil {
		log.Fatal("Failed to get database instance:", err)
	}

	// 设置连接池
	sqlDB.SetMaxIdleConns(10)           // 最大空闲连接数
	sqlDB.SetMaxOpenConns(100)          // 最大打开连接数
	sqlDB.SetConnMaxLifetime(time.Hour) // 连接最大存活时间

	// 自动迁移
	err = AutoMigrate()
	if err != nil {
		log.Fatal("Failed to migrate database:", err)
	}

	log.Println("Database connection established successfully")

}

func AutoMigrate() error {
	return db.AutoMigrate(
		&model.User{},
		&model.Group{},
		// 其他模型...
	)
}

// GetDB 获取数据库实例
func GetDB() *gorm.DB {
	return db
}

func Close() {
	sqlDB, err := db.DB()
	if err == nil {
		sqlDB.Close()
	}
}
